// Plupload 上传

// 默认配置
var settings = {
	runtimes : 'html5',
	browse_button : 'pickfile',
	container: document.getElementById('fileupload'),
	url : HOME_URL + '/admin/upload',
	multipart_params: {'type': 1},
	thumb: false,
	init: {
		PostInit: function(up) {
			up._container = $(up.getOption('container'));
			up._btn = $(up.getOption('browse_button'));
			var type = up._container.find('.upload').data('type');
			var params = {};

			type && (params.type = type);
			up.getOption('thumb') && (params.thumb = up.getOption('thumb')); 

			up.setOption('multipart_params', params);
		},
		FilesAdded: function(up, files) {
			up._container.siblings('.upload-message').html('<span>正在上传...</span>');
			up.start();
		},
		UploadProgress: function(up, file) {},
            FileUploaded: function(up, file, data) {
				var response = $.parseJSON(data.response);
				var name = up._container.find('.upload').data('name');
				var marks = up._container.find('.upload').data('marks') ? up._container.find('.upload').data('marks') : name;

				if (response.state != 'SUCCESS') {
					alert(response.state);
					return false;
				}

				var html = "<div class='thumbnail' data-img='"
						 + response.path +"'>"
						 + "<input type='hidden' name='" + name + "' value='" + response.path + "'>"
						 + "<a class='thumbnail-img' href='"+ HOME_URL +'/' + response.path+"' rel='prettyPhoto[" + marks +"]'><img src='" 
						 + HOME_URL + '/' + (response.thumb ? response.thumb : response.path)
						 + "'></a><a href='javascript:;' class='thumbnail-remove'>删除</a></div>";
				up._container.siblings('.attachments').append(html).show();
				$("a[rel^='prettyPhoto']").prettyPhoto({social_tools: ''});
            },		
		UploadComplete: function(up, file) {
			up._container.siblings('.upload-message').html('');

			if (up._container.siblings('.attachments').find('.thumbnail').length == 5) {
				up._btn.addClass('disabled');
				up.disableBrowse(true);
			}
		},
		Error: function(up, err) {
			alert('文件上传失败');
			// alert(JSON.stringify(err));
		},
	},
};

var uploader = function(config) {
	var options = {};
	$.extend(options, settings, config);

	var up = new plupload.Uploader(options);
	up.init();
}